#include "RequestManager.hpp"

#include <iostream>

/* constructor */
RequestManager::RequestManager(ClientManager* clientManager)
{
	this->clientManager=clientManager;
	pthread_cond_init(&this->cond,NULL);
	pthread_mutex_init(&this->lock,NULL);
}

/* destructor */
RequestManager::~RequestManager()
{
	// TODO : free the FIFO 
}

/* external method : add a request (lock) */
void RequestManager::addRequest(Client* client,char* request)
{
	// DEBUG
	std::cout << "request added : " << request << std::endl;

	Request temp(client,request);
	this->requestQueue.push(temp);
}

/* thread run : handle requests -> client vars + client sendList */
void RequestManager::run()
{
	/* DEBUG */
	std::cout << "RequestManager : STARTED\n";
	

	while(true)
	{
		// cond wait if queue is empty
		pthread_mutex_lock(&this->lock);
		while(this->requestQueue.empty())
			pthread_cond_wait(&this->cond,&this->lock);
		pthread_mutex_unlock(&this->lock);
		
		this->handleRequest(this->requestQueue.front());
		this->requestQueue.pop();
	}
}

/* internal method : handle request ~ clients + client.SendList + game... */
int RequestManager::handleRequest(Request& requestObject)
{
	Client* client=requestObject.client;
	char* request=requestObject.request;

	/* DEBUG */
	std::cout << "handle request : " << request << std::endl;
	std::cout << "\tfor client : " << client->sfd << std::endl;

	// TODO : request => xml => parse => handle (return -1 if error) => add to sendLists

	return 0;
}

/**
 * Request constructor
 **/
Request::Request(Client*& client,char*& request)
{
	this->request=(char*)malloc(4096);
	this->client=client;
	strcpy(this->request,request);
}

/**
 * Request destructor
 **/
Request::~Request()
{
//TODO : ????? double free ? -> error (requestQueue.pop())
//	free(this->request);	
}
